package com.syg.servlet13_cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
@WebServlet("/loginCookie")
public class _01_Login_cookie extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sdf.format(new Date());
        Cookie cookie1 = new Cookie("LastTime",dateStr);
        resp.addCookie(cookie1);
        Cookie[] cookies = req.getCookies();
        if(null!=cookies){
            for (Cookie cookie : cookies) {
                if ("LastTime".equals(cookie.getName())){
                    resp.getOutputStream().write(("您上次访问的时间是:"+cookie.getValue()).getBytes());
                    break;
                }else{

                    resp.getOutputStream().write(("现在时间是:"+cookie1.getValue()).getBytes());
                }
            }
        }else{
            resp.getOutputStream().write(("现在时间是:"+cookie1.getValue()).getBytes());
        }

    }
}
